package com.fortune.app.models;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 塔罗牌解读系统实现类
 */
public class TarotDivination {
    private Map<String, Map<String, Object>> tarotCards;
    private Map<String, Map<String, Object>> spreads;
    
    public TarotDivination() {
        initTarotCards();
        initSpreads();
    }
    
    /**
     * 初始化塔罗牌数据
     */
    private void initTarotCards() {
        tarotCards = new HashMap<>();
        
        // 大阿卡纳牌（22张）
        initMajorArcana();
        
        // 小阿卡纳牌（56张）
        initMinorArcana();
    }
    
    /**
     * 初始化大阿卡纳牌
     */
    private void initMajorArcana() {
        // 愚者
        Map<String, Object> fool = new HashMap<>();
        fool.put("name", "The Fool");
        fool.put("chinese_name", "愚者");
        fool.put("upright", "新的开始，冒险，自发性，潜力，自由");
        fool.put("reversed", "鲁莽，冒险，愚蠢的选择，漫无目的");
        fool.put("image", "fool.jpg");
        fool.put("element", "风");
        tarotCards.put("0", fool);
        
        // 魔术师
        Map<String, Object> magician = new HashMap<>();
        magician.put("name", "The Magician");
        magician.put("chinese_name", "魔术师");
        magician.put("upright", "创造力，意志力，技巧，行动力，专注");
        magician.put("reversed", "操纵，计划不周，潜能未开发，技能欠缺");
        magician.put("image", "magician.jpg");
        magician.put("element", "火");
        tarotCards.put("1", magician);
        
        // 女祭司
        Map<String, Object> priestess = new HashMap<>();
        priestess.put("name", "The High Priestess");
        priestess.put("chinese_name", "女祭司");
        priestess.put("upright", "直觉，潜意识，神秘，内在声音，智慧");
        priestess.put("reversed", "秘密，断绝联系，忽视直觉，表面信息");
        priestess.put("image", "priestess.jpg");
        priestess.put("element", "水");
        tarotCards.put("2", priestess);
        
        // 其他大阿卡纳牌...
        // 世界
        Map<String, Object> world = new HashMap<>();
        world.put("name", "The World");
        world.put("chinese_name", "世界");
        world.put("upright", "完成，整合，成就，旅行，和谐");
        world.put("reversed", "未完成，短视，缺乏收尾，停滞");
        world.put("image", "world.jpg");
        world.put("element", "土");
        tarotCards.put("21", world);
    }
    
    /**
     * 初始化小阿卡纳牌
     */
    private void initMinorArcana() {
        // 权杖（Wands）- 对应火元素
        for (int i = 1; i <= 10; i++) {
            Map<String, Object> card = new HashMap<>();
            card.put("name", i + " of Wands");
            card.put("chinese_name", "权杖" + i);
            card.put("suit", "wands");
            card.put("element", "火");
            card.put("upright", getWandsMeaning(i, true));
            card.put("reversed", getWandsMeaning(i, false));
            card.put("image", "wands_" + i + ".jpg");
            tarotCards.put("wands_" + i, card);
        }
        
        // 圣杯（Cups）- 对应水元素
        for (int i = 1; i <= 10; i++) {
            Map<String, Object> card = new HashMap<>();
            card.put("name", i + " of Cups");
            card.put("chinese_name", "圣杯" + i);
            card.put("suit", "cups");
            card.put("element", "水");
            card.put("upright", getCupsMeaning(i, true));
            card.put("reversed", getCupsMeaning(i, false));
            card.put("image", "cups_" + i + ".jpg");
            tarotCards.put("cups_" + i, card);
        }
        
        // 宝剑（Swords）- 对应风元素
        for (int i = 1; i <= 10; i++) {
            Map<String, Object> card = new HashMap<>();
            card.put("name", i + " of Swords");
            card.put("chinese_name", "宝剑" + i);
            card.put("suit", "swords");
            card.put("element", "风");
            card.put("upright", getSwordsMeaning(i, true));
            card.put("reversed", getSwordsMeaning(i, false));
            card.put("image", "swords_" + i + ".jpg");
            tarotCards.put("swords_" + i, card);
        }
        
        // 星币（Pentacles）- 对应土元素
        for (int i = 1; i <= 10; i++) {
            Map<String, Object> card = new HashMap<>();
            card.put("name", i + " of Pentacles");
            card.put("chinese_name", "星币" + i);
            card.put("suit", "pentacles");
            card.put("element", "土");
            card.put("upright", getPentaclesMeaning(i, true));
            card.put("reversed", getPentaclesMeaning(i, false));
            card.put("image", "pentacles_" + i + ".jpg");
            tarotCards.put("pentacles_" + i, card);
        }
        
        // 宫廷牌 - 侍从、骑士、王后、国王
        // 这里只添加一个示例，实际需要添加所有16张宫廷牌
        Map<String, Object> wandsPage = new HashMap<>();
        wandsPage.put("name", "Page of Wands");
        wandsPage.put("chinese_name", "权杖侍从");
        wandsPage.put("suit", "wands");
        wandsPage.put("element", "火");
        wandsPage.put("upright", "热情，探索，能量，消息");
        wandsPage.put("reversed", "缺乏方向，拖延，不稳定");
        wandsPage.put("image", "wands_page.jpg");
        tarotCards.put("wands_page", wandsPage);
    }
    
    /**
     * 初始化塔罗牌阵
     */
    private void initSpreads() {
        spreads = new HashMap<>();
        
        // 三张牌阵
        Map<String, Object> threeCard = new HashMap<>();
        threeCard.put("name", "三张牌阵");
        threeCard.put("description", "简单而有效的牌阵，可以代表过去、现在和未来，或者问题、行动和结果。");
        
        List<Map<String, String>> threeCardPositions = new ArrayList<>();
        Map<String, String> position1 = new HashMap<>();
        position1.put("name", "过去/问题");
        position1.put("description", "代表过去的影响或当前问题的根源");
        threeCardPositions.add(position1);
        
        Map<String, String> position2 = new HashMap<>();
        position2.put("name", "现在/行动");
        position2.put("description", "代表当前情况或需要采取的行动");
        threeCardPositions.add(position2);
        
        Map<String, String> position3 = new HashMap<>();
        position3.put("name", "未来/结果");
        position3.put("description", "代表可能的结果或未来发展");
        threeCardPositions.add(position3);
        
        threeCard.put("positions", threeCardPositions);
        spreads.put("three_card", threeCard);
        
        // 凯尔特十字牌阵
        Map<String, Object> celticCross = new HashMap<>();
        celticCross.put("name", "凯尔特十字牌阵");
        celticCross.put("description", "最经典的塔罗牌阵之一，提供全面的分析。");
        
        List<Map<String, String>> celticPositions = new ArrayList<>();
        // 添加10个位置...
        Map<String, String> celticPosition1 = new HashMap<>();
        celticPosition1.put("name", "当前状况");
        celticPosition1.put("description", "代表咨询者目前的状况");
        celticPositions.add(celticPosition1);
        
        // 添加其他位置...
        
        celticCross.put("positions", celticPositions);
        spreads.put("celtic_cross", celticCross);
        
        // 关系牌阵
        Map<String, Object> relationship = new HashMap<>();
        relationship.put("name", "关系牌阵");
        relationship.put("description", "专门用于分析人际关系的牌阵。");
        
        List<Map<String, String>> relationshipPositions = new ArrayList<>();
        // 添加6个位置...
        
        relationship.put("positions", relationshipPositions);
        spreads.put("relationship", relationship);
    }
    
    /**
     * 获取权杖牌的含义
     */
    private String getWandsMeaning(int number, boolean isUpright) {
        String[][] meanings = {
            {"开始，灵感，创造力", "虚假的开始，延迟，缺乏灵感"},
            {"计划，决定，发现", "恐惧做决定，拖延，不稳定"},
            {"扩展，成长，合作", "延迟，缺乏合作，障碍"},
            {"稳定，和谐，家庭", "不稳定，不和谐，缺乏支持"},
            {"冲突，竞争，挑战", "避免冲突，退缩，内部斗争"},
            {"胜利，成功，公众认可", "延迟，骄傲，过度自信"},
            {"毅力，挑战，竞争", "精疲力竭，放弃，被压倒"},
            {"速度，行动，旅行", "延迟，挫折，缺乏方向"},
            {"准备，防御，坚持", "顽固，偏执，缺乏准备"},
            {"负担，责任，压力", "压力过大，崩溃，解脱"}
        };
        
        if (number >= 1 && number <= 10) {
            return meanings[number - 1][isUpright ? 0 : 1];
        }
        return "未知";
    }
    
    /**
     * 获取圣杯牌的含义
     */
    private String getCupsMeaning(int number, boolean isUpright) {
        String[][] meanings = {
            {"新的感情，直觉，创造力", "情感枯竭，创造力阻塞，孤独"},
            {"和谐，伙伴关系，吸引力", "失衡，分离，误解"},
            {"庆祝，友谊，合作", "过度放纵，疏远，孤独"},
            {"沉思，冥想，无聊", "行动，新机会，摆脱停滞"},
            {"失落，悲伤，遗憾", "接受，前进，找到希望"},
            {"怀旧，回忆，重聚", "停滞于过去，拒绝前进，幻想"},
            {"幻想，选择，欺骗", "现实，明确选择，决心"},
            {"放弃，转变，倦怠", "喜悦，回归，重新参与"},
            {"满足，情感满足，愿望实现", "物质主义，表面满足，过度放纵"},
            {"和谐，完美，幸福家庭", "破碎的家庭，不和谐，价值观不同"}
        };
        
        if (number >= 1 && number <= 10) {
            return meanings[number - 1][isUpright ? 0 : 1];
        }
        return "未知";
    }
    
    /**
     * 获取宝剑牌的含义
     */
    private String getSwordsMeaning(int number, boolean isUpright) {
        String[][] meanings = {
            {"清晰，真相，突破", "混乱，虚假，不公正"},
            {"僵局，决定，和平", "紧张，恐惧，不诚实"},
            {"心碎，悲伤，分离", "恢复，宽恕，释放"},
            {"休息，恢复，冥想", "倦怠，压力，缺乏进展"},
            {"冲突，争论，竞争", "和解，解决，释放紧张"},
            {"过渡，旅程，离开", "阻碍，混乱，延迟"},
            {"欺骗，策略，秘密计划", "揭露，诚实，放弃计划"},
            {"限制，困境，受害者心态", "自由，新视角，接受"},
            {"焦虑，恐惧，噩梦", "希望，清晰，面对恐惧"},
            {"结束，失败，痛苦", "恢复，希望，新开始"}
        };
        
        if (number >= 1 && number <= 10) {
            return meanings[number - 1][isUpright ? 0 : 1];
        }
        return "未知";
    }
    
    /**
     * 获取星币牌的含义
     */
    private String getPentaclesMeaning(int number, boolean isUpright) {
        String[][] meanings = {
            {"机会，繁荣，新的财富", "错失机会，物质损失，贪婪"},
            {"平衡，适应，时间管理", "失衡，混乱，优先级错误"},
            {"技能，合作，商业", "缺乏团队合作，混乱，低质量工作"},
            {"安全，保守，控制", "风险，过度控制，错失机会"},
            {"贫困，孤立，担忧", "恢复，新机会，精神富足"},
            {"慷慨，帮助，分享", "自私，债务，不平等"},
            {"耐心，长期视野，投资", "缺乏耐心，短视，机会损失"},
            {"技能，勤奋，细节", "完美主义，工作狂，缺乏深度"},
            {"富足，奢侈，自给自足", "物质损失，缺乏安全感，孤立"},
            {"财富，家庭，传统", "家庭冲突，财务损失，破产"}
        };
        
        if (number >= 1 && number <= 10) {
            return meanings[number - 1][isUpright ? 0 : 1];
        }
        return "未知";
    }
    
    /**
     * 抽取塔罗牌并进行解读
     * 
     * @param spreadName 牌阵名称
     * @param birthDate 用户生日，格式为"YYYY-MM-DD"
     * @param currentTime 当前时间，格式为"YYYY-MM-DD HH:MM:SS"
     * @param question 用户提出的问题
     * @return 塔罗牌解读结果
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> drawCards(String spreadName, String birthDate, String currentTime, String question) {
        try {
            // 解析生日和当前时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            
            Date birthDt = dateFormat.parse(birthDate);
            Date currentDt = timeFormat.parse(currentTime);
            
            // 设置随机种子，确保结果的一致性
            Calendar birthCal = Calendar.getInstance();
            Calendar currentCal = Calendar.getInstance();
            birthCal.setTime(birthDt);
            currentCal.setTime(currentDt);
            
            int seed = birthCal.get(Calendar.YEAR) + birthCal.get(Calendar.MONTH) + birthCal.get(Calendar.DAY_OF_MONTH) +
                       currentCal.get(Calendar.YEAR) + currentCal.get(Calendar.MONTH) + currentCal.get(Calendar.DAY_OF_MONTH) +
                       currentCal.get(Calendar.HOUR_OF_DAY) + currentCal.get(Calendar.MINUTE) + currentCal.get(Calendar.SECOND) +
                       question.length();
            
            Random random = new Random(seed);
            
            // 获取牌阵信息
            Map<String, Object> spread = spreads.get(spreadName);
            if (spread == null) {
                spread = spreads.get("three_card");
            }
            
            List<Map<String, String>> positions = (List<Map<String, String>>) spread.get("positions");
            
            // 创建牌组
            List<String> deck = new ArrayList<>(tarotCards.keySet());
            
            // 洗牌
            for (int i = deck.size() - 1; i > 0; i--) {
                int j = random.nextInt(i + 1);
                String temp = deck.get(i);
                deck.set(i, deck.get(j));
                deck.set(j, temp);
            }
            
            // 抽取牌
            List<Map<String, Object>> drawnCards = new ArrayList<>();
            for (int i = 0; i < positions.size(); i++) {
                // 抽一张牌
                String cardKey = deck.get(i);
                Map<String, Object> card = new HashMap<>(tarotCards.get(cardKey));
                
                // 随机决定正位或逆位
                boolean isUpright = random.nextBoolean();
                card.put("position", isUpright);
                card.put("position_name", isUpright ? "正位" : "逆位");
                card.put("meaning", isUpright ? card.get("upright") : card.get("reversed"));
                
                // 添加位置信息
                card.put("spread_position", positions.get(i).get("name"));
                card.put("position_description", positions.get(i).get("description"));
                
                drawnCards.add(card);
            }
            
            // 生成整体解读
            String overallInterpretation = generateOverallInterpretation(drawnCards, question);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            
            Map<String, Object> spreadInfo = new HashMap<>();
            spreadInfo.put("name", spread.get("name"));
            spreadInfo.put("description", spread.get("description"));
            result.put("spread", spreadInfo);
            
            result.put("question", question);
            result.put("cards", drawnCards);
            result.put("overall_interpretation", overallInterpretation);
            result.put("divination_time", currentTime);
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("birth_date", birthDate);
            result.put("user_info", userInfo);
            
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }
    
    /**
     * 生成整体解读
     */
    private String generateOverallInterpretation(List<Map<String, Object>> cards, String question) {
        // 分析牌面元素分布
        Map<String, Integer> elements = new HashMap<>();
        elements.put("火", 0);
        elements.put("水", 0);
        elements.put("风", 0);
        elements.put("土", 0);
        
        int majorArcanaCount = 0;
        Map<String, Integer> suits = new HashMap<>();
        suits.put("wands", 0);
        suits.put("cups", 0);
        suits.put("swords", 0);
        suits.put("pentacles", 0);
        
        for (Map<String, Object> card : cards) {
            if (card.containsKey("element")) {
                String element = (String) card.get("element");
                elements.put(element, elements.getOrDefault(element, 0) + 1);
            }
            
            String name = (String) card.get("name");
            if (name != null && (name.startsWith("The ") || name.matches("\\d+"))) {
                majorArcanaCount++;
            }
            
            if (card.containsKey("suit")) {
                String suit = (String) card.get("suit");
                suits.put(suit, suits.getOrDefault(suit, 0) + 1);
            }
        }
        
        // 确定主导元素
        String dominantElement = "火";
        int maxCount = elements.get("火");
        for (Map.Entry<String, Integer> entry : elements.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                dominantElement = entry.getKey();
            }
        }
        
        // 根据问题类型和牌面分布生成解读
        StringBuilder interpretation = new StringBuilder();
        
        // 根据问题关键词确定问题类型
        String questionLower = question.toLowerCase();
        if (questionLower.contains("爱情") || questionLower.contains("感情") || 
            questionLower.contains("关系") || questionLower.contains("婚姻")) {
            
            if (elements.get("水") > elements.get("火")) {
                interpretation.append("在感情方面，您目前处于一个情感丰富但可能缺乏激情的阶段。");
            } else {
                interpretation.append("您的感情生活充满激情，但可能需要更多的情感交流和理解。");
            }
            
            if (suits.get("cups") > suits.get("wands")) {
                interpretation.append("牌面显示您的情感世界丰富多彩，但可能需要更多的行动来表达。");
            } else {
                interpretation.append("您在感情中表现积极主动，但可能需要更多地关注伴侣的情感需求。");
            }
        } else if (questionLower.contains("事业") || questionLower.contains("工作") || 
                   questionLower.contains("职业") || questionLower.contains("学业")) {
            
            if (elements.get("火") > elements.get("土")) {
                interpretation.append("在事业方面，您充满热情和创造力，但可能需要更加踏实和耐心。");
            } else {
                interpretation.append("您在工作中表现稳重踏实，但可能需要更多的创新和冒险精神。");
            }
            
            if (suits.get("pentacles") > suits.get("wands")) {
                interpretation.append("牌面显示您注重物质成就和稳定性，这将为您带来长期的职业发展。");
            } else {
                interpretation.append("您的职业发展充满活力和机遇，但需要更加关注长期规划和稳定性。");
            }
        } else if (questionLower.contains("财富") || questionLower.contains("金钱") || 
                   questionLower.contains("财运") || questionLower.contains("投资")) {
            
            if (elements.get("土") > elements.get("风")) {
                interpretation.append("在财富方面，您注重稳健和积累，这将为您带来长期的财务安全。");
            } else {
                interpretation.append("您的财务状况可能面临变化和挑战，需要更加谨慎和务实的态度。");
            }
            
            if (suits.get("pentacles") > 1) {
                interpretation.append("牌面显示您有良好的财务管理能力，继续保持将带来丰厚回报。");
            } else {
                interpretation.append("您可能需要更加关注财务规划和管理，避免不必要的风险和损失。");
            }
        } else {
            // 通用解读
            interpretation.append("牌面整体呈现").append(dominantElement).append("元素主导，表示");
            if (dominantElement.equals("火")) {
                interpretation.append("您当前充满热情、创造力和行动力。");
            } else if (dominantElement.equals("水")) {
                interpretation.append("您当前情感丰富，直觉敏锐，人际关系和谐。");
            } else if (dominantElement.equals("风")) {
                interpretation.append("您当前思维活跃，沟通顺畅，但可能面临决策挑战。");
            } else if (dominantElement.equals("土")) {
                interpretation.append("您当前注重实际和稳定，物质基础良好，但可能缺乏变化。");
            }
        }
        
        // 根据大阿卡纳牌的数量添加解读
        if (majorArcanaCount > cards.size() / 2) {
            interpretation.append("\n\n牌面中大阿卡纳牌占比较高，表明您正处于人生的重要转折点，外部力量和命运的影响较大。这段时期的经历和决定可能对您的未来产生深远影响。");
        }
        
        // 添加建议
        interpretation.append("\n\n根据牌面，建议您：");
        
        if (elements.get("火") > elements.get("水")) {
            interpretation.append("\n- 保持热情的同时，多关注自己和他人的情感需求");
        } else {
            interpretation.append("\n- 在情感丰富的同时，适当增加行动力和决断力");
        }
        
        if (elements.get("土") > elements.get("风")) {
            interpretation.append("\n- 在稳健踏实的基础上，增加一些创新思维和灵活性");
        } else {
            interpretation.append("\n- 在思维活跃的同时，注重实际行动和落地执行");
        }
        
        // 根据牌面特点添加具体建议
        List<Map<String, Object>> specialCards = new ArrayList<>();
        for (Map<String, Object> card : cards) {
            String name = (String) card.get("name");
            if (name != null && (name.equals("The Tower") || name.equals("Death") || 
                name.equals("The Devil") || name.equals("The Star") || name.equals("The Sun"))) {
                specialCards.add(card);
            }
        }
        
        if (!specialCards.isEmpty()) {
            interpretation.append("\n\n特别提示：");
            for (Map<String, Object> card : specialCards) {
                String name = (String) card.get("name");
                String chineseName = (String) card.get("chinese_name");
                
                if (name.equals("The Tower")) {
                    interpretation.append("\n- ").append(chineseName).append("牌提示您可能面临突然的变化或挑战，保持冷静和适应力至关重要");
                } else if (name.equals("Death")) {
                    interpretation.append("\n- ").append(chineseName).append("牌象征转变和重生，而非负面结局，拥抱变化将带来新的机遇");
                } else if (name.equals("The Devil")) {
                    interpretation.append("\n- ").append(chineseName).append("牌提醒您注意可能的束缚或不健康的依恋，寻求自由和平衡");
                } else if (name.equals("The Star")) {
                    interpretation.append("\n- ").append(chineseName).append("牌带来希望和灵感，相信自己的直觉和内在指引");
                } else if (name.equals("The Sun")) {
                    interpretation.append("\n- ").append(chineseName).append("牌预示成功和喜悦，保持乐观积极的态度将带来更多好运");
                }
            }
        }
        
        return interpretation.toString();
    }
}
